package com.freedomlane.pgen;

import java.util.Random;
import java.util.Date;


/**
 * This class can be used to generate a password String that can be used by a
 * user for any external usage.  The user may choose the password to be made of
 * alphabetic characters, with both lower and upper case, with numbers, and
 * special charcters.  To a certain extent a password generated will be
 * randomized.  Users may opt the passwords generated not to be repeated to add
 * more security.
 *
 * @author Sandeep Ellawala
 *
 * @version 1.0
 * 
 * @since 1.0
 */
public class PasswordGenerator {
    //Flag variables indicating the composition of the password.
    private boolean withLowerCase;
    private boolean withUpperCase;
    private boolean withDigits;
    private boolean withSpecials;
    private boolean repeated;

    private int length;

    private String password;

    private PasswordLevel level;

    //The set of character tokens that will be put togethr to generate a
    //password in the given specification.
    private final static char [] TOKENS = {
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
        'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3',
        '4', '5', '6', '7', '8', '9', '`', '~', '!', '@', '#', '$', '%', '^',
        '&', '*', '(', ')', '-', '_', '+', '=', '[', '{', ']', '}', ',', '<',
        '.', '>', '/', '?', '\\', '|'
    };

    //The lower and upper bounds for the token categories.
    private final static int LOWER_START = 0;
    private final static int UPPER_START = 26;
    private final static int DIGIT_START = 52;
    private final static int SPECIAL_START = 62;

    private final static int DEFAULT_LENGTH = 8;

    private final static PasswordLevel DEFAULT_LEVEL = PasswordLevel.LOWER;

    /**
     * This constructor can be used to to build a PasswordGenerator with the
     * default password level and default password length.
     */
    public PasswordGenerator() {
        this(DEFAULT_LEVEL, DEFAULT_LENGTH);
    }

    /**
     * This constructor can be used to build a PasswordGenerator with the given
     * password level and default password length.
     *
     * @param level The level of complexitiy for the passwords generated by this
     * PasswordGenerator.
     */
    public PasswordGenerator(PasswordLevel level) {
        this(level, DEFAULT_LENGTH);
    }

    /**
     * This constructor can be used to build a PasswordGenerator with the
     * default password level and the given password length.
     *
     * @param length The length of the passwords generated by this
     * PasswordGenerator.
     */
    public PasswordGenerator(int length) {
        this(DEFAULT_LEVEL, length);
    }

    /**
     * This constructor can be used to build a PasswordGenerator with the given
     * password level and the given password length.
     *
     * @param level The level of complexity of the passwords generated by this
     * PasswordGenerator.
     *
     * @param length The length of the passwords generated by this
     * PasswordGenerator.
     */
    public PasswordGenerator(PasswordLevel level, int length) {
        if (level != null) {
            if (length > 0) {
                this.level = level;
                this.length = length;

                this.initializeLevel();
            } else {
                this.level = level;
                this.length = DEFAULT_LENGTH;

                this.initializeLevel();
            }
        } else {
            if (length > 0) {
                this.level = DEFAULT_LEVEL;
                this.length = length;

                this.initializeLevel();
            } else {
                this.level = DEFAULT_LEVEL;
                this.length = DEFAULT_LENGTH;

                this.initializeLevel();
            }
        }
    }

    /**
     * Check if the passwords generated by this PasswordGenerator have lowercase
     * alphabetic characters in it.
     *
     * @return True if the passwords generated by this PasswordGenerator have
     * lowercase alphabetic characters in them.
     * 
     * @return False if the passwords generated by this PasswordGenerator does
     * not have lowercase alphabetic characters in them.
     */
    public boolean isWithLowerCase() {
        return this.withLowerCase;
    }

    /**
     * Set if the passwords generated by this PasswordGenerator have lowercse
     * alphabetic characters in them.
     *
     * @param withLowerCase Set to true if the passwords generated by this
     * PasswordGenerator should have lowercase alphabetic characters in them.
     */
    public void setWithLowerCase(boolean withLowerCase) {
        this.withLowerCase = withLowerCase;

        this.initializeLevel();
    }

    /**
     * Check if the passwords generated by this PasswordGenerator have uppercase
     * alphabetic characters in them.
     *
     * @return True if passwords generated by this PasswordGenerator have
     * uppercase alphabetic characters in them.
     *
     * @return False if passwords generated by this PasswordGenerator does not
     * have uppercase alphabetic characters in them.
     */
    public boolean isWithUpperCase() {
        return this.withUpperCase;
    }

    /**
     * Set if the passwords generated by this PasswordGenerator have uppsercase
     * alphabetic characters in them.
     *
     * @param withUpperCase Set to true if the passwords generated by this
     * PasswordGenerator should have uppercase alphabetic characters in them.
     */
    public void setWithUpperCase(boolean withUpperCase) {
        this.withUpperCase = withUpperCase;

        this.initializeLevel();
    }

    /**
     * Check if the passwords generated by this PasswordGenerator have numbers
     * in them.
     *
     * @return True if the passwords generated by this PasswordGenerator have
     * numbers in them.
     *
     * @return False if the passwords generated by this PasswordGenerator does
     * not have numbers in them.
     */
    public boolean isWithDigits() {
        return this.withDigits;
    }


    /**
     * Set if the passwords generated by this PasswordGenerator have digits in
     * them or not.
     *
     * @param withDigits Set to true if passwords generated by this
     * PasswordGenerator have numbers in them.
     */
    public void setWithDigits(boolean withDigits) {
        this.withDigits = withDigits;

        this.initializeLevel();
    }


    /**
     * Check if the passwords generated by this PasswordGenerator have special
     * characters in them.
     *
     * @return True if passwords generated by this PasswordGenerator have
     * special characters in them.
     *
     * @return False if passwords generated by this PasswordGenerator does not
     * have special characters in them.
     */
    public boolean isWithSpecials() {
        return this.withSpecials;
    }


    /**
     * Set if the passwords generated by this PasswordGenerator have special
     * characters in them or not.
     *
     * @param withSpecials Set to true if the passwords generated by this
     * PasswordGenerator have special characters in them.
     */
    public void setWithSpecials(boolean withSpecials) {
        this.withSpecials = withSpecials;

        this.initializeLevel();
    }


    /**
     * Check if the passwords generated by this PasswordGenerator can repeat the
     * ones that have previously been generated by the same PasswordGenerator.
     *
     * @return True if the passwords generated by this PasswordGenerator can
     * repeat the ones that have previously been generated by the same
     * PasswordGenerator.
     *
     * @return False if the passwords generated by this PasswordGenerator cannot
     * repeat the ones that have previously been generated by the same
     * PasswordGenerator.
     */
    public boolean isRepeated() {
        return this.repeated;
    }


    /**
     * Set if the passwords generated by this PasswordGenerator can repeat the
     * ones that have previously been generated by the same PasswordGenerator.
     *
     * @param repeated Set to true if the passwords generated by this
     * PasswordGenerator can repeat the ones that have previously been created
     * by the same PasswordGenerator.
     */
    public void setRepeated(boolean repeated) {
        this.repeated = repeated;
    }


    /**
     * Get the length of the passwords generated by this PasswordGenerator.
     *
     * @return The length of the passwords generated by this PasswordGenerator.
     */
    public int getLength() {
        return this.length;
    }


    /**
     * Set the length of the passwords generated by this PassworGenerator.
     * 
     * @param length The length of the passwords generated by this
     * PasswordGenerator.  If this is set to a value less than or equal to zero,
     * then the length of the passwords is set to the default length for the
     * passwords.
     */
    public void setLength(int length) {
        if (length > 0) {
            this.length = length;
        } else {
            this.length = DEFAULT_LENGTH;
        }
    }


    /**
     * Get a password that was generated by this PasswordGenerator.
     *
     * @return The password that was generated by this PasswordGenerator.
     *
     * @return null if there was no password generated so far by this
     * PasswordGenerator.
     */
    public String getPassword() {
        String password = null;

        do {
            password = this.generatePassword(false);
            
            if (password != null && password.length() == this.length) {
                break;
            }
        } while (true);
        
        //Now we seem to have a password that is neither null nor of invalid
        //length.
        
        if (this.repeated) {
            //No need to check if this had already been created.  But we must
            //update the database to make sure that all generated passwords are
            //recorded.

            DBAccess.recordPassword(password);

            this.password = password;
        } else {
            //We have to ensure that the passwords are not repeated.

            if (!DBAccess.isAlreadyCreated(password)) {
                //The password is not found in the existing records.  So I
                //must save it to keep track of all the generated passwords.

                DBAccess.recordPassword(password);

                this.password = password;
            } else {
                this.password = "";
            }
        }

        return this.password;
    }


    /**
     * Set a new password for this PasswordGenerator.  This method is both
     * deprecated and inactive since the version 1.0 for the obvious reason of
     * a password supposed to be generated and not set.
     *
     * @param password The password to be set for this PasswordGenerator.
     *
     * @deprecated
     */
    public void setPassword(String password) {
        //Inactive
    }


    /**
     * Get the level of password strength at which the passwords of this
     * PasswordGenerator are generated.
     *
     * @return The level of strength of the passwords generated by this
     * PasswordGenerator.
     */
    public PasswordLevel getLevel() {
        return this.level;
    }


    /**
     * Set the level of password strength at which the passwords of this
     * PasswordGenerator are generated.
     *
     * @param level Set to the level of strength required by the passwords of
     * this PasswordGenerator.
     */
    public void setLevel(PasswordLevel level) {
        if (level != null) {
            this.level = level;

            //I really don't think I have to explain each and every CASE, since
            //it is self explanatory.  If you find it not so, I guess you have
            //brush up on your Java as well as English.
            switch (this.level) {
                case NONE:
                    //TODO: A future version may assume the NONE to be the same
                    //as the default level and make changes to the following
                    //flag variables.
                    this.withLowerCase = false;
                    this.withUpperCase = false;
                    this.withDigits = false;
                    this.withSpecials = false;
                    break;
                case LOWER:
                    this.withLowerCase = true;
                    this.withUpperCase = false;
                    this.withDigits = false;
                    this.withSpecials = false;
                    break;
                case UPPER:
                    this.withLowerCase = false;
                    this.withUpperCase = true;
                    this.withDigits = false;
                    this.withSpecials = false;
                    break;
                case DIGIT:
                    this.withLowerCase = false;
                    this.withUpperCase = false;
                    this.withDigits = true;
                    this.withSpecials = false;
                    break;
                case SPECIAL:
                    this.withLowerCase = false;
                    this.withUpperCase = false;
                    this.withDigits = false;
                    this.withSpecials = true;
                    break;
                case LOWER_UPPER:
                    this.withLowerCase = true;
                    this.withUpperCase = true;
                    this.withDigits = false;
                    this.withSpecials = false;
                    break;
                case LOWER_DIGIT:
                    this.withLowerCase = true;
                    this.withUpperCase = false;
                    this.withDigits = true;
                    this.withSpecials = false;
                    break;
                case LOWER_SPECIAL:
                    this.withLowerCase = true;
                    this.withUpperCase = false;
                    this.withDigits = false;
                    this.withSpecials = true;
                    break;
                case UPPER_DIGIT:
                    this.withLowerCase = false;
                    this.withUpperCase = true;
                    this.withDigits = true;
                    this.withSpecials = false;
                    break;
                case UPPER_SPECIAL:
                    this.withLowerCase = false;
                    this.withUpperCase = true;
                    this.withDigits = false;
                    this.withSpecials = true;
                    break;
                case DIGIT_SPECIAL:
                    this.withLowerCase = false;
                    this.withUpperCase = false;
                    this.withDigits = true;
                    this.withSpecials = true;
                    break;
                case LOWER_UPPER_DIGIT:
                    this.withLowerCase = true;
                    this.withUpperCase = true;
                    this.withDigits = true;
                    this.withSpecials = false;
                    break;
                case LOWER_UPPER_SPECIAL:
                    this.withLowerCase = true;
                    this.withUpperCase = true;
                    this.withDigits = false;
                    this.withSpecials = true;
                    break;
                case LOWER_DIGIT_SPECIAL:
                    this.withLowerCase = true;
                    this.withUpperCase = false;
                    this.withDigits = true;
                    this.withSpecials = true;
                    break;
                case UPPER_DIGIT_SPECIAL:
                    this.withLowerCase = false;
                    this.withUpperCase = true;
                    this.withDigits = true;
                    this.withSpecials = true;
                    break;
                case LOWER_UPPER_DIGIT_SPECIAL:
                    this.withLowerCase = true;
                    this.withUpperCase = true;
                    this.withDigits = true;
                    this.withSpecials = true;
                    break;
            }
        }
    }


    /**
     * This method is used to initialize the level based on the settings
     * indicated by the lowercase, uppercase, digit, and special character
     * flags.
     */
    private void initializeLevel() {
        //I wonder if I should use the mutator of level when I set it within
        //this methods.  I see no reason so far as to why I should do so.
        
        if (this.withLowerCase) {
            if (this.withUpperCase) {
                if (this.withDigits) {
                    if (this.withSpecials) {
                        this.level = PasswordLevel.LOWER_UPPER_DIGIT_SPECIAL;
                    } else {
                        this.level = PasswordLevel.LOWER_UPPER_DIGIT;
                    }
                } else {
                    if (this.withSpecials) {
                        this.level = PasswordLevel.LOWER_UPPER_SPECIAL;
                    } else {
                        this.level = PasswordLevel.LOWER_UPPER;
                    }
                }
            } else {
                if (this.withDigits) {
                    if (this.withSpecials) {
                        this.level = PasswordLevel.LOWER_DIGIT_SPECIAL;
                    } else {
                        this.level = PasswordLevel.LOWER_DIGIT;
                    }
                } else {
                    if (this.withSpecials) {
                        this.level = PasswordLevel.LOWER_SPECIAL;
                    } else {
                        this.level = PasswordLevel.LOWER;
                    }
                }
            }
        } else {
            if (this.withUpperCase) {
                if (this.withDigits) {
                    if (this.withSpecials) {
                        this.level = PasswordLevel.UPPER_DIGIT_SPECIAL;
                    } else {
                        this.level = PasswordLevel.UPPER_DIGIT;
                    }
                } else {
                    if (this.withSpecials) {
                        this.level = PasswordLevel.UPPER_SPECIAL;
                    } else {
                        this.level = PasswordLevel.UPPER;
                    }
                }
            } else {
                if (this.withDigits) {
                    if (this.withSpecials) {
                        this.level = PasswordLevel.DIGIT_SPECIAL;
                    } else {
                        this.level = PasswordLevel.DIGIT;
                    }
                } else {
                    if (this.withSpecials) {
                        this.level = PasswordLevel.SPECIAL;
                    } else {
                        //TODO: A future version might change this to the
                        //default level and adjust the flag variables
                        //accordingly.
                        this.level = PasswordLevel.NONE;
                    }
                }
            }
        }
    }

    private String generatePassword(boolean withDefaults) {
        StringBuffer pwd = null;

        int pwdLength = 0;

        PasswordLevel pwdLevel = null;

        if (withDefaults) {
            pwdLength = this.DEFAULT_LENGTH;
            pwdLevel = this.DEFAULT_LEVEL;
        } else {
            pwdLength = this.length;
            pwdLevel = this.level;
        }

        pwd = new StringBuffer(pwdLength);

        int index = -1;
        int upperLimit = -1;
        int lowerLimit = -1;

        //Set the upper limit for the index.
        switch (pwdLevel) {
            case LOWER:
                upperLimit = this.UPPER_START;
                break;
            case UPPER:
            case LOWER_UPPER:
                upperLimit = this.DIGIT_START;
                break;
            case DIGIT:
            case LOWER_DIGIT:
            case LOWER_UPPER_DIGIT:
            case UPPER_DIGIT:
                upperLimit = this.SPECIAL_START;
                break;
            default:
                upperLimit = TOKENS.length;
                break;
        }

        //Set the lower limit for the index.
        switch (pwdLevel) {
            case SPECIAL:
                lowerLimit = this.SPECIAL_START;
                break;
            case DIGIT:
            case DIGIT_SPECIAL:
                lowerLimit = this.DIGIT_START;
                break;
            case UPPER:
            case UPPER_DIGIT:
            case UPPER_DIGIT_SPECIAL:
            case UPPER_SPECIAL:
                lowerLimit = this.UPPER_START;
                break;
            default:
                lowerLimit = this.LOWER_START;
                break;
        }

        int ctr = 0;
        
        while (ctr < pwdLength) {
            Random randomGenerator = new Random(new Date().getTime());

            try {
                //Without this sleep, the processor works just too fast for the
                //seed to get changed.  So the password will most probably be
                //just the same character repeating over the length of the
                //password, which I believe is to be an undesirable condition.
                Thread.sleep(1000);
            } catch (Exception exc) {
                //Ignore
            }

            do {
                index = randomGenerator.nextInt(upperLimit);

                if (index >= lowerLimit && index < upperLimit) {
                    break;
                }
            } while (true);

            pwd.append(this.TOKENS[index]);

            ctr++;
        }

        return ((pwd == null)?"":pwd.toString());
    }
}